import axios from 'axios';
import { Message } from 'element-ui';

const http = axios.create({
    baseURL:``,
    timeout: 1000 * 30
})


//请求拦截器
http.interceptors.request.use(function(req){
    //如果有token存在每次请求时就放入请求头中
    if(window.sessionStorage.getItem("tokenStr")){
        req.headers['token'] = JSON.parse(window.sessionStorage.getItem("tokenStr"));
    }
    return req;
},error=>{
    console.log(error);
})

//响应拦截器
http.interceptors.response.use(function(resp){
    //响应正确判断返回的状态码
    if(resp.status && resp.status == 200){
        if(resp.data.code == 500 || resp.data.code == 401 || resp.data.code == 403 || resp.data.code == 1500){
            Message.error({
                message: resp.data.msg,
                type: 'error'
            });
            return;
        }
    }
    return resp.data;
},error=>{
    //接口访问不到
    if(error.response.code == 504 || error.response.code == 404){
        Message.error({
            message: '服务器开小差了',
            type: 'error'
          });
    }else if(error.response.code == 403){
        Message.error({
            message: '权限不足',
            type: 'error'
        });
    }else if(error.response.code == 401){
        Message.error({
            message: '尚未登录，请先登录',
            type: 'error'
        });
        this.$router.replace('/');
    }else{
        if(error.response.data.message){
            Message.error({
                message: error.response.data.msg,
                type: 'error'
            });
        }else{
            Message.error({
                message: '未知错误',
                type: 'error'
            });
        }
    }
    return;
})

export default http;